package com.ehotting.edsta.file.service;

import com.alibaba.fastjson.JSON;
import com.ehotting.eaf.core.domain.model.LoginUser;
import com.ehotting.eaf.core.utils.DateUtils;
import com.ehotting.eaf.core.utils.StringUtils;
import com.ehotting.eaf.security.service.TokenService;
import com.ehotting.edsta.file.config.MinioConfig;
import com.ehotting.edsta.file.utils.FileUploadUtils;
import com.ehotting.edsta.file.utils.MinioUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Minio 文件存储
 * 
 * @author edsta
 */
@RefreshScope
@Primary
@Service
@Slf4j
public class MinioSysFileServiceImpl implements ISysFileService
{
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient client;

    /**
     * 内部上传地址
     */
    @Value("${minio.endpoint}")
    private String endpoint;

    @Autowired
    private TokenService tokenService;

    /**
     * 电路文件上传
     * @param file
     * @param relativePath
     * @return
     * @throws Exception
     */
    @Override
    public String uploadCircuitFile(MultipartFile file,String relativePath) throws Exception
    {
        String bucketName = "circuitdesign";
        MinioUtils minioUtils = new MinioUtils(client, bucketName);
        minioUtils.existBucket(bucketName);

        Path path = Paths.get(relativePath);
        String parent = "";
        if(path.getParent()!=null){
            parent = path.getParent().toString().replace("\\","/")+"/";
        }
        String s = path.getFileName().toString();
        String fileName = s.substring(0,s.lastIndexOf('.'))
                .replace("-", "_")
                .replace("__", "_")
                .replace(".","");
        //修改后缀
        String fileSuffix = s.substring(s.lastIndexOf('.'))
                .replace(".xlsx", ".xls");

        String newRelativePath = (parent + fileName +fileSuffix).replace("_.", ".");

        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(newRelativePath)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);
        return minioConfig.getUrl() + "/" + bucketName + "/" + newRelativePath;
    }

    /**
     * 本地文件上传接口
     * 上传到默认桶，如果没有该桶，则创建
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String upload(MultipartFile file) throws Exception
    {
        String fileName = FileUploadUtils.extractFilename(file);
        String bucketName = minioConfig.getBucketName();
        MinioUtils minioUtils = new MinioUtils(client, bucketName);
        minioUtils.existBucket(bucketName);
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);
        return minioConfig.getUrl() + "/" + bucketName + "/" + fileName;
    }

    /**
     * 本地文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadByFilepath(MultipartFile file, String bucketName, String filepath) throws Exception
    {
        String absFilename = "";
        if (StringUtils.isNotEmpty(filepath)){
            absFilename+=filepath;
        }
        absFilename += file.getOriginalFilename();
        if (StringUtils.isEmpty(bucketName)){
            bucketName = minioConfig.getBucketName();
        }
        MinioUtils minioUtils = new MinioUtils(client, bucketName);
        minioUtils.existBucket(bucketName);
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(absFilename)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);

        String url = minioConfig.getDownloadUrl() + "/" + bucketName + "/" + absFilename;
        if (bucketName.equalsIgnoreCase("cae")){
            // 如果是cae的上传，则需要重新组装url
            LoginUser loginUser = tokenService.getLoginUser();
            if (loginUser!=null){
                url += "&&token="+loginUser.getToken();
            }
        }
        return url;
    }

    /**
     *
     * @param files
     * @param bucketName
     * @param filepath
     * @param isUseDownloadUrl 是否使用downloadUrl
     * @return
     * @throws Exception
     */
    @Override
    public String uploadFiles(List<MultipartFile> files, String bucketName, String filepath, boolean isUseDownloadUrl) throws Exception {
        List<String> filepathList = new ArrayList<>();
//        log.info("bucketName:{},filepath:{}",bucketName,filepath);

        if (StringUtils.isEmpty(bucketName)){
            bucketName = minioConfig.getBucketName();
        }
        MinioUtils minioUtils = new MinioUtils(client, bucketName);
        minioUtils.existBucket(bucketName);

        for (MultipartFile file : files) {
            if (StringUtils.isEmpty(filepath)){
                filepath = "/";
            }
            String absFilename = filepath + File.separator + file.getOriginalFilename();
//            log.info("file.getOriginalFilename():{}",file.getOriginalFilename());

            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(absFilename)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();
            client.putObject(args);
            filepathList.add(absFilename);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("url",isUseDownloadUrl?minioConfig.getDownloadUrl():minioConfig.getUrl());
        map.put("fileList",filepathList);
        return JSON.toJSONString(map);
    }

    @Override
    public String uploadFileByModule(MultipartFile file, String moduleName, String accessKey, String secretKey) throws Exception {
        MinioClient minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();

        String fileName = FileUploadUtils.extractFilename(file);
        MinioUtils minioUtils = new MinioUtils(minioClient, moduleName);
        minioUtils.existBucket(moduleName);

        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(moduleName)
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        minioClient.putObject(args);
        return minioConfig.getUrl() + "/" + moduleName + "/" + fileName;
    }
}
